package com.wyd.common.sm;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.sun.xml.internal.ws.util.StreamUtils;
import com.wyd.common.util.SM4Utils;
import org.apache.poi.util.IOUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Hex;
import org.junit.jupiter.api.Test;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;

public class Sm4Utils {

    private static final String ENCODING = "UTF-8";
    public static final String ALGORIGTHM_NAME = "SM4";
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS7Padding";
    public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding";
    public static final int DEFAULT_KEY_SIZE = 128;

    public Sm4Utils() {
    }

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     *  @Description:生成ecb暗号
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName,BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORIGTHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /**
     *  @Description:自动生成密钥
     */
    public static byte[] generateKey() throws Exception {
        return generateKey(DEFAULT_KEY_SIZE);
    }

    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORIGTHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }


    /**
     *  @Description:加密
     */
    public static String encryptEcb(String hexKey, String paramStr, String charset) throws Exception {
        String cipherText = "";
        if (null != paramStr && !"".equals(paramStr)) {
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            charset = charset.trim();
            if (charset.length() <= 0) {
                charset = ENCODING;
            }
            byte[] srcData = paramStr.getBytes(charset);
            byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
            cipherText = ByteUtils.toHexString(cipherArray);
        }
        return cipherText;
    }

    /**
     *  @Description:加密模式之ecb
     */
    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        byte[] bs = cipher.doFinal(data);
        return bs;
    }
    
    public static String encrypt_Cbc_Padding(String hexKey, String paramStr) throws Exception {
        byte[] key = ByteUtils.fromHexString(hexKey);
        byte[] data = paramStr.getBytes(StandardCharsets.UTF_8);
        
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_CBC_PADDING,BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORIGTHM_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, sm4Key, new IvParameterSpec(key));
        byte[] bs = cipher.doFinal(data);
        return ByteUtils.toHexString(bs);
    }
    
    public static String decrypt_Cbc_Padding(String hexKey, String paramStr) throws Exception {
        byte[] key = ByteUtils.fromHexString(hexKey);
        byte[] data = Hex.decode(paramStr);
//        byte[] data = paramStr.getBytes(StandardCharsets.UTF_8);
        
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_CBC_PADDING,BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORIGTHM_NAME);
        cipher.init(Cipher.DECRYPT_MODE, sm4Key, new IvParameterSpec(key));
        byte[] bs = cipher.doFinal(data);
        
        return new String(bs);
    }

    /**
     *  @Description:sm4解密
     */
    public static String decryptEcb(String hexKey, String cipherText, String charset) throws Exception {
        String decryptStr = "";
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        charset = charset.trim();
        if (charset.length() <= 0) {
            charset = ENCODING;
        }
        decryptStr = new String(srcData, charset);
        return decryptStr;
    }

    /**
     *  @Description:解密
     */
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    /**
     *  @Description:密码校验
     */
    public static boolean verifyEcb(String hexKey,String cipherText,String paramStr) throws Exception {
        boolean flag = false;
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        byte[] decryptData = decrypt_Ecb_Padding(keyData,cipherData);
        byte[] srcData = paramStr.getBytes(ENCODING);
        flag = Arrays.equals(decryptData,srcData);
        return flag;
    }

    /**
     *  @Description:测试类
     */
    public static void main(String[] args) throws Exception {
        final byte[] bytes = Sm4Utils.generateKey();

        System.out.println(Hex.toHexString(bytes));

        try {
            String json = "123456asdasd啊手动阀计划";
//            String json = "{\"name\":\"color\",\"sex\":\"man\"}";
            // 自定义的32位16进制密钥
            String key = "8de678042d9b9a392ef8b69937c23109";
//            String key = "cc9368581322479ebf3e79348a2757d9";
            String cipher = Sm4Utils.encryptEcb(key, json,ENCODING);
            System.out.println(cipher);
            System.out.println(Sm4Utils.verifyEcb(key, cipher, json));
            String d = Sm4Utils.decryptEcb(key, cipher,ENCODING);
            System.out.println("解密：" + d.equals(json));
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void testFront() throws Exception {
        String key = "FA171555405706F73D7B973DB89F0B47";
        String data = "6c249673dc8f59a159a434e4e76f7fdb";

        final byte[] bytes = ByteUtils.fromHexString(key);
        final byte[] decode = Hex.decode(key);

        System.out.println(Arrays.equals(bytes, decode));

        final String s = decrypt_Cbc_Padding(key, data);

        System.out.println(s);;
    }

    @Test
    public void hutoolTest() {
        String content ="test中文";
        SymmetricCrypto sm4 = SmUtil.sm4();

        final String algorithm = sm4.getSecretKey().getAlgorithm();
        System.out.println(algorithm);
        System.out.println(Hex.toHexString(sm4.getSecretKey().getEncoded()));

        String encryptHex = sm4.encryptHex(content);
        String decryptStr = sm4.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);

        System.out.println(decryptStr.equals(content));
    }

    @Test
    public void speedTestHuTool() throws Exception {
        String file = "C:\\Users\\jzkr\\Desktop\\blank4.txt";
        String key = "d8613c869eed3a10298ccd01e770faaa";

        final byte[] bytes = IoUtil.readBytes(new FileInputStream(file));
//        final byte[] bytes = StreamUtils.copyToByteArray(new FileInputStream(file));



        final long l = System.currentTimeMillis();

        // ECB CBC 对加密速度没有太大影响
//        final SM4 sm4 = new SM4(Mode.ECB, Padding.PKCS5Padding, Hex.decode(key));
        final SM4 sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, Hex.decode(key));

        
        
//        SymmetricCrypto sm4 = SmUtil.sm4(Hex.decode(key));
        final String encrypt = sm4.encryptHex(bytes);
        final long l2 = System.currentTimeMillis();

        System.out.println("加密用时：" + (l2 - l));
        System.out.println("加密用时：" + (l2 - l) /1000 + "秒");

        IoUtil.writeUtf8(new FileOutputStream("C:\\Users\\jzkr\\Desktop\\blank3.txt"), true, encrypt);

        System.out.println("结束");
    }

    @Test
    public void speedTest2() throws Exception {
        String file = "C:\\Users\\jzkr\\Desktop\\blank4.txt";
        String key = "d8613c869eed3a10298ccd01e770faaa";

        final byte[] bytes = IoUtil.readBytes(new FileInputStream(file));
//        final byte[] bytes = StreamUtils.copyToByteArray(new FileInputStream(file));

//        SymmetricCrypto sm4 = SmUtil.sm4();

        final long l = System.currentTimeMillis();
//        final String encrypt = sm4.encryptHex(bytes);
        final byte[] encrypt1 = SM4Utils.encrypt(bytes, Hex.decode(key), SM4Utils.SM4ModeAndPaddingEnum.SM4_CBC_PKCS5Padding, Hex.decode(key));
        final String encrypt = org.apache.commons.codec.binary.Hex.encodeHexString(encrypt1);
//        final String encrypt = Hex.toHexString(encrypt1);
        final long l2 = System.currentTimeMillis();

        System.out.println("加密用时：" + (l2 - l));
        System.out.println("加密用时：" + (l2 - l) /1000 + "秒");

        final long d1 = System.currentTimeMillis();
        final byte[] decrypt = SM4Utils.decrypt(encrypt1, Hex.decode(key), SM4Utils.SM4ModeAndPaddingEnum.SM4_CBC_PKCS5Padding, Hex.decode(key));
        final long d2 = System.currentTimeMillis();

        System.out.println("解密用时：" + (d2 - d1));
        
        System.out.println(Arrays.equals(bytes, decrypt));

        IoUtil.writeUtf8(new FileOutputStream("C:\\Users\\jzkr\\Desktop\\blank3.txt"), true, encrypt);

        System.out.println("结束");
    }

    @Test
    public void speedTest3() throws Exception {
        String file = "C:\\Users\\jzkr\\Desktop\\blank4.txt";
        String key = "d8613c869eed3a10298ccd01e770faaa";

        final byte[] bytes = IoUtil.readBytes(new FileInputStream(file));

        final long l = System.currentTimeMillis();
        final String encrypt = com.wyd.common.sm.test.SM4Utils.encryptCbcPadding(key, bytes);
        final long l2 = System.currentTimeMillis();

        System.out.println("加密用时：" + (l2 - l));
        System.out.println("加密用时：" + (l2 - l) /1000 + "秒");

        final long d1 = System.currentTimeMillis();
        final String decrypt = com.wyd.common.sm.test.SM4Utils.decryptCbcPadding(key, encrypt);
        final long d2 = System.currentTimeMillis();

        System.out.println("解密用时：" + (d2 - d1));
        
        System.out.println(Arrays.equals(bytes, decrypt.getBytes(StandardCharsets.UTF_8)));

        IoUtil.writeUtf8(new FileOutputStream("C:\\Users\\jzkr\\Desktop\\blank3.txt"), true, encrypt);

        System.out.println("结束");
    }
}
